﻿using Apache.NMS.ActiveMQ.Util;
using IdGen;
using Mall.DomainModel;
using Mall.DomainModel.Dto.Query;
using Mall.DomainModel.IRepository;
using Mall.Repository;
using Mall.Service;
using Mall.Service.Dto;
using Mall.Web.ViewModel;
using Mall.Web.ViewModel.Input;
using Mall.Web.ViewModel.Query;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace Mall.Web.Controllers
{
    [Route("mall/[controller]/[action]")]
    [ApiController]
    public class ShipperManageUserController : BaseController
    {
        private readonly IShipperManageUserService _shipperManageUserService ;

        public ShipperManageUserController(IShipperManageUserService shipperManageUserService)
        {
            _shipperManageUserService = shipperManageUserService;
        }
        [HttpGet("GetShipperManageUser")]
        public async Task<ShipperManageUserListVM> GetShipperManageUser([FromQuery]ShipperManageUserVM vm)
        {
            var queryInput = new ShipperManageUserQueryInput()
            {
                 Id=vm.Id,
            };
            var list = await _shipperManageUserService.GetList(queryInput);
            var result = new ShipperManageUserListVM
            {
                Data = list.Items.Select(x => new ShipperManageUserItemVM
                {
                    RealName = x.RealName,
                    Phone = x.Phone,
                    UserName = x.UserName,
                    Password = x.Password,
                    IsEnabled = x.IsEnabled,
                    RoleNames = x.RoleNames,
                    EditPassWordTime = x.EditPassWordTime != null ? x.EditPassWordTime : null
                }).ToList(),
                Total = list.TotalCount
            };
            return result;
        }

        [HttpPost("AddShipperManageUser")]
        public async Task<OutputVM> Add([FromBody] ShipperManageUserInputVM user)
        {
            var input = new ShipperManageUser()
            {
                Id = SnowflakeIdGenerator.GenerateId(),
                RealName = user.RealName,
                Phone = user.Phone,
                UserName = user.UserName,
                Password = user.Password,
                RoleNames = user.RoleNames,
                IsEnabled= true,
                CreatorUserId = 1,
                EditPassWordTime=null,
                CreationTime = DateTime.Now
            };
            var id = await _shipperManageUserService.Add(input);
            return new OutputVM()
            {
                ExtData = id,
                ErrorMsg = id ? "添加成功" : "添加失败",
            };
        }

        [HttpPost("UpdateShipperManageUser")]
        public async Task<OutputVM> Update([FromBody] ShipperManageUserInputVM user)
        {
            var input = new ShipperManageUser()
            {
                Id = user.Id,
                RealName = user.RealName,
                Phone = user.Phone,
                UserName = user.UserName,
                Password = user.Password,
                RoleNames = user.RoleNames,
                IsEnabled = user.IsEnabled,
                LastModifierUserId = 1,
                LastModificationTime = DateTime.Now,
                EditPassWordTime=DateTime.Now,
            };
            var update = await _shipperManageUserService.Update(input);
            return new OutputVM()
            {
                ExtData = update,
                ErrorMsg = update ? "修改成功" : "修改失败"
            };
        }


        #region 雪花算法
        private static class SnowflakeIdGenerator
        {
            private static readonly IdGen.IdGenerator _generator;

            static SnowflakeIdGenerator()
            {
                // 配置说明：
                // - machineId: 机器ID（0-1023），分布式环境中每台服务器需不同
                // - 时间基准（Epoch）：建议用项目启动时间
                var options = new IdGeneratorOptions(
                    idStructure: new IdStructure(41, 10, 12), // 41位时间戳 + 10位机器ID + 12位序列号
                    timeSource: new DefaultTimeSource(DateTime.UtcNow.Date)
                );

                _generator = new IdGen.IdGenerator(0, options); // 单机环境可用0
            }

            public static long GenerateId() => _generator.CreateId();
        }
        #endregion
    }
}
